package com.kj.xuyuan.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kj.xuyuan.R;
import com.kj.xuyuan.adapter.DynamicAdapter;
import com.kj.xuyuan.adapter.DynamicCommentAdapter;
import com.kj.xuyuan.adapter.DynamicDetailsLikePeopleAdapter;
import com.kj.xuyuan.adapter.DynamicImageAdapter;
import com.kj.xuyuan.base.BaseActivity;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.mine.HomePageActivity;
import com.kj.xuyuan.model.DynamicDetailsBean;
import com.kj.xuyuan.model.WebviewBean;
import com.kj.xuyuan.pay.PayListenerUtils;
import com.kj.xuyuan.pop.UniversalClickPopWindow;
import com.kj.xuyuan.util.DisplayUtil;
import com.kj.xuyuan.util.GlideUtils;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.PhotoSelectSingleUtile;
import com.kj.xuyuan.util.PhotoViewActivity;
import com.kj.xuyuan.util.ScreenUtils;
import com.kj.xuyuan.util.StringUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.kj.xuyuan.widget.FullyGridLayoutManager;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.IMCenter;

/**
 * 动态详情
 */
public class DynamicDetailsActivity extends BaseActivity implements View.OnLayoutChangeListener, ViewTreeObserver.OnGlobalLayoutListener{

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_like_peoples)
    ImageView ivLikePeoples;
    @BindView(R.id.iv_comment_list)
    ImageView ivCommentList;
    @BindView(R.id.tv_report)
    TextView tvReport;
    @BindView(R.id.tv_line)
    TextView tvLine;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_like_or_chat)
    TextView tvLikeOrChat;
    @BindView(R.id.tv_tag)
    TextView tvTag;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.rv_image)
    RecyclerView rvImage;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.tv_like)
    TextView tvLike;
    @BindView(R.id.rv_like_people)
    RecyclerView rvLikePeople;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.ed_input)
    EditText edInput;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.cl_bottom)
    ConstraintLayout clBottom;

    private int dynamicId;
    private DynamicDetailsBean data;
    private int softKeyBoardHeight;
    private View rootView;
    private int rootViewVisibleHeight;
    private boolean keyboardIsShow;

    public static void actionStar(Context context, int dynamicId){
        Intent intent = new Intent(context,DynamicDetailsActivity.class);
        intent.putExtra("dynamicId",dynamicId);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_dynamic_details;
    }

    @Override
    protected void initView() {
        dynamicId = getIntent().getIntExtra("dynamicId",-1);
        if(dynamicId == -1){
            ToastUtil.showDataErrorToast(context);
            finish();
            return;
        }

        rootView = getWindow().getDecorView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(this);
        rootView.addOnLayoutChangeListener(this);

        getDynamicDetails();
    }

    private void getDynamicDetails() {
        showDialog();
        Map map = new HashMap();
        //是否点赞过本条动态 0否 1是
        map.put("id",dynamicId+"");
        OkGoUtil.postRequest(getContext(), UrlConstants.DYNAMIC_DETAILS, map, new JsonCallback<BaseModel<DynamicDetailsBean>>() {
            @Override
            public void onSuccess(Response<BaseModel<DynamicDetailsBean>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        data = response.body().getData();
                        setView(response.body().getData());
                    }else{
                        ToastUtil.showToast(getContext(),response.body().getMsg());
                    }
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<BaseModel<DynamicDetailsBean>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                dismissDialog();
            }
        });
    }

    private void setView(DynamicDetailsBean data) {
        tvName.setText(data.getDetail().getUser().getNickname());
        tvLocation.setText(data.getDetail().getAddress());
        if(data.getDetail().getTopic() != null && !StringUtils.isEmpty(data.getDetail().getTopic().getTitle())){
            tvTag.setVisibility(View.VISIBLE);
            tvTag.setText(data.getDetail().getTopic().getTitle());
        }else{
            tvTag.setVisibility(View.GONE);
        }
        tvContent.setText(data.getDetail().getContent());
        tvComment.setText(data.getDetail().getComment()+"");
        tvTime.setText(data.getDetail().getCreatetime()+data.getDetail().getView()+"浏览");
        GlideUtils.loadCircleImage(context, UrlConstants.Base_Http+data.getDetail().getUser().getAvatar(),ivHead);

        tvSex.setText(data.getDetail().getUser().getYears());
        Drawable sexDrawable = null;
        if(data.getDetail().getUser().getGender().equals("1")){//1男2女
            tvSex.setBackgroundResource(R.drawable.shape_blue_20);
            sexDrawable = getResources().getDrawable(R.mipmap.icon_boy);
        }else{

            sexDrawable = getResources().getDrawable(R.mipmap.icon_girl);
        }
        sexDrawable.setBounds(0,0,sexDrawable.getMinimumWidth(),sexDrawable.getMinimumHeight());
        tvSex.setCompoundDrawables(sexDrawable,null,null,null);

        Drawable likeDrawable = null;
        if(data.getDetail().getIs_like_message() == 0){//是否点过喜欢 0否 1是
            tvLike.setText("喜欢");
            likeDrawable = getResources().getDrawable(R.mipmap.icon_like);
        }else{
            tvLike.setText("去聊天");
            likeDrawable = getResources().getDrawable(R.mipmap.icon_msg);
        }
        likeDrawable.setBounds(0,0,likeDrawable.getMinimumWidth(),likeDrawable.getMinimumHeight());
        tvLikeOrChat.setCompoundDrawables(likeDrawable,null,null,null);

        tvLike.setText(data.getDetail().getLike()+"");
        Drawable niceDrawable = null;
        if(data.getDetail().getIs_like() == 0){//是否点赞过本条动态 0否 1是
            niceDrawable = getResources().getDrawable(R.mipmap.icon_nice);
        }else{
            niceDrawable = getResources().getDrawable(R.mipmap.icon_nice_red);
        }
        niceDrawable.setBounds(0,0,niceDrawable.getMinimumWidth(),niceDrawable.getMinimumHeight());
        tvLike.setCompoundDrawables(niceDrawable,null,null,null);

        if(StringUtils.isEmpty(data.getDetail().getImage())){
            rvImage.setVisibility(View.GONE);
        }else{
            DynamicImageAdapter adapter = new DynamicImageAdapter();
            rvImage.setVisibility(View.VISIBLE);
            rvImage.setLayoutManager(new FullyGridLayoutManager(context,3));
            if(rvImage.getItemDecorationCount() == 0){
                rvImage.addItemDecoration(new GridSpacingItemDecoration(3, DisplayUtil.dp2px(context,5),false));
            }
            rvImage.setAdapter(adapter);
            String[] str = data.getDetail().getImage().split(",");
            ArrayList<String> images = new ArrayList<>();
            for(int i = 0;i<str.length;i++){
                images.add(str[i]);
            }
            adapter.setNewData(images);

            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    PhotoViewActivity.actionStar(getContext(),images,position);
                }
            });
        }

        setNiceRecyclerView(data.getLike_list());
        setCommentRecyclerView(data.getComment_list());
    }

    //评论列表
    private void setCommentRecyclerView(List<DynamicDetailsBean.CommentListBean> comment_list) {
        if(comment_list == null || comment_list.size() == 0){
            rvComment.setVisibility(View.GONE);
            ivCommentList.setVisibility(View.GONE);
        }else{
            rvComment.setVisibility(View.VISIBLE);
            ivCommentList.setVisibility(View.VISIBLE);
        }

        rvComment.setLayoutManager(new LinearLayoutManager(context));
        DynamicCommentAdapter adapter = new DynamicCommentAdapter();
        rvComment.setAdapter(adapter);
        adapter.setNewData(comment_list);
    }

    //点赞列表
    private void setNiceRecyclerView(List<DynamicDetailsBean.LikeListBean> like_list) {
        if(like_list == null || like_list.size() == 0){
            rvLikePeople.setVisibility(View.GONE);
            ivLikePeoples.setVisibility(View.GONE);
            tvLine.setVisibility(View.GONE);
        }else{
            rvLikePeople.setVisibility(View.VISIBLE);
            ivLikePeoples.setVisibility(View.VISIBLE);
            tvLine.setVisibility(View.VISIBLE);
        }

        rvLikePeople.setLayoutManager(new LinearLayoutManager(context,RecyclerView.HORIZONTAL,false));
        DynamicDetailsLikePeopleAdapter adapter = new DynamicDetailsLikePeopleAdapter();
        rvLikePeople.setAdapter(adapter);
        adapter.setNewData(like_list);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return -1;
    }


    @OnClick({R.id.iv_back, R.id.tv_report, R.id.iv_head, R.id.tv_like_or_chat,R.id.tv_like,R.id.tv_send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_report:
                getReportData();
                break;
            case R.id.iv_head:
                HomePageActivity.actionStar(context,data.getDetail().getUser().getId());
                break;
            case R.id.tv_like_or_chat:
                //是否点过喜欢 0否 1是
                if(data.getDetail().getIs_like_message() == 0){//没点过，走喜欢逻辑
                    like();
                }else{//点过，跳转聊天页

                }
                break;
            case R.id.tv_send:
                publishComment();
                break;
            case R.id.tv_like:
                dynamicLike();
                break;
        }
    }

    private void getReportData() {
        OkGoUtil.postRequest(getContext(), UrlConstants.REPORT_LIST, null, new JsonCallback<BaseModel<List<WebviewBean>>>() {
            @Override
            public void onSuccess(Response<BaseModel<List<WebviewBean>>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        popReportWindow(response.body().getData());
                    }else{
                        ToastUtil.showToast(getContext(),response.body().getMsg());
                    }

                }
            }

            @Override
            public void onError(Response<BaseModel<List<WebviewBean>>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void popReportWindow(List<WebviewBean> reports) {
        List<String> list = new ArrayList<>();
        for(int i = 0;i<reports.size();i++){
            list.add(reports.get(i).getContent());
        }
        UniversalClickPopWindow popWindow = new UniversalClickPopWindow(context,list);
        popWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM,0,0);
        popWindow.setAnimationStyle(R.style.popwindow_center_anim_style);
        popWindow.setItemClickListener(new UniversalClickPopWindow.ItemClickListener() {
            @Override
            public void click(int position) {
                report(reports.get(position).getId());
            }
        });
    }

    private void report(int id) {
        Map map = new HashMap();
        map.put("for_user_id",data.getDetail().getUser().getId()+"");
        map.put("ids",id+"");
        OkGoUtil.postRequest(getContext(), UrlConstants.REPORT, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        finish();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void publishComment() {
        String comment = edInput.getText().toString().trim();
        if(StringUtils.isEmpty(comment)){
            ToastUtil.showToast(context,"评论未填写");
            return;
        }

        showDialog();
        Map map = new HashMap();
        map.put("type","2");
        map.put("comment_id",data.getDetail().getId()+"");
        map.put("content",comment);
        OkGoUtil.postRequest(getContext(), UrlConstants.PUBLISH_DYNAMIC, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        edInput.setText("");
                        getDynamicDetails();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                dismissDialog();
            }
        });
    }

    private void dynamicLike() {
        showDialog();
        Map map = new HashMap();
        map.put("type",data.getDetail().getIs_like() == 0 ? "1" : "0");
        map.put("topic_comment_id",data.getDetail().getId()+"");
        OkGoUtil.postRequest(getContext(), UrlConstants.DYNAMIC_LIKE, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        getDynamicDetails();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                dismissDialog();
            }
        });
    }

    private void like() {
        showDialog();
        Map map = new HashMap();
        map.put("for_user_id",data.getDetail().getUser().getId()+"");
        OkGoUtil.postRequest(getContext(), UrlConstants.LIKE, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        getDynamicDetails();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                dismissDialog();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        rootView.removeOnLayoutChangeListener(this);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //获取View可见区域的bottom
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        if(bottom!=0 && oldBottom!=0 && bottom - rect.bottom - ScreenUtils.getBottomStatusHeight(context) <= 0){
            //软键盘隐藏
            if(keyboardIsShow){
                setInputViewMargin(0);
                keyboardIsShow = false;
                LogUtils.e(TAG,"----------");
            }
        }else{
            if(!keyboardIsShow){
                keyboardIsShow = true;
                setInputViewMargin(softKeyBoardHeight);
                LogUtils.e(TAG,"*************");
            }
        }
    }

    @Override
    public void onGlobalLayout() {
        if (softKeyBoardHeight != 0)
            return;

        //获取当前根视图在屏幕上显示的大小
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        int visibleHeight = r.height();
        if (rootViewVisibleHeight == 0) {
            rootViewVisibleHeight = visibleHeight;
            return;
        }

        //根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变
        if (rootViewVisibleHeight == visibleHeight) {
            return;
        }
        //根视图显示高度变小超过200，可以看作软键盘显示了
        if (rootViewVisibleHeight - visibleHeight > 200) {
            softKeyBoardHeight = rootViewVisibleHeight - visibleHeight - ScreenUtils.getNavigationBarHeight(context)+ScreenUtils.getBottomStatusHeight(context)- DisplayUtil.dp2px(context,33);
            setInputViewMargin(softKeyBoardHeight);
            return;
        }
    }

    private void setInputViewMargin(int margin) {
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams)clBottom.getLayoutParams();
        layoutParams.bottomMargin = margin;
        clBottom.setLayoutParams(layoutParams);
    }
}